#include "loopdbl.h"

loopdbl*  create(void)
{
    loopdbl* head;
    head = (loopdbl*)malloc(sizeof(loopdbl));
    if(head==NULL)
    {
        printf("%s error!!\n",__func__);
        return NULL;
    }

    head->data = 0;
    head->pre = head;
    head->next = head;

    return head;
}

int loopdblshow(loopdbl*head)//遍历
{
    if(head==NULL)
    {
        printf("show error\n");
        return -1;
    }
    loopdbl*save =head;    
    while(head->next!=save)
    {
    
        printf(" %d",head->next->data);
         head = head->next;       
    }
    putchar(10);
        return 0;
}

int loopinserthead(loopdbl* head, datatype data)//头插法
{
    loopdbl * temp ;
    temp = (loopdbl*)malloc(sizeof(loopdbl));
    if(temp == NULL)
    {
        printf(" loopinserthead error\n");
        return -1;
    }
     
     temp->data = data;

     temp->next = head->next;
     temp->pre = head;
     temp->next->pre = temp;
     head->next = temp;

     return 0;
}

int loopinserttail(loopdbl* head, datatype data)//尾插法
{
    loopdbl* temp;
    temp  = (loopdbl*)malloc(sizeof(loopdbl));
    if(temp == NULL)
    {
        printf(" loopinserthead error\n");
        return -1;
    }
    loopdbl* save;
    save = head;
    while(head->next!= save)
    {
        head = head->next;
    }
    temp->data = data;

    temp->next = head->next;
    temp->pre = head;
    head->next->pre = temp;
    head->next = temp;
    return 0;
}

int insertbypos(loopdbl* head,datatype data, int pos)//按位置插入
{
    loopdbl * temp;
    loopdbl * save;
    save = head;
    temp = (loopdbl*)malloc(sizeof(loopdbl));
     if(temp == NULL)
    {
        printf(" loopinserthead error\n");
        return -1;
    }
    if(pos<0)
    {
        printf("插入有误\n");
    }

    while(head->next!=save || pos ==0)
    {
        if(pos!=0)
        {
            head=head->next;
            pos--;
        }
        if(pos==0)
        {
            temp->data =data;

            temp->next = head->next;
            temp->pre = head;
            head->next->pre = temp;
            head->next = temp;
            return 0;
        }
    }
    printf("插入有误\n");
    return -1;
}

